<?php 

namespace Weixin\Controller;
use Common\Controller\WeixinBase;
use Common\Model\Model;

class TryController extends WeixinbaseController
{
    
    protected function _initialize() {
        parent::_initialize();
        //更新状态,把过期的产品更新为过期
        $arr['iffinish'] = true;
        $map['end_time'] = array('LT',time());
        M('TryItems')->where($map)->save($arr);
        $data['iffinish'] = false;
        $where['end_time'] = array('GT',time());
        M('TryItems')->where($where)->save($data);
    
    }
    
    /**
     * 试用列表
     */
    public function index()
    {
        
        $filed=array('tryid','title','image','requestnum','price','trynum','end_time');
        $hotList = M('TryItems')->field($filed)->where(array('status'=>true,'ifhot'=>true,'iffinish'=>false))->limit(10)->select();
        if($hotList)
        {
            $tempHot = array();
            $num = 0;
            foreach($hotList as $k => $v)
            {
                $tempHot[$num][] = $v;
                if(($k + 1) % 2 == 0)
                {
                    $num++;
                }
            }
            $hotList = $tempHot;
        }
        $this->assign('hotList', $hotList);
        $newList = M('TryItems')->field($filed)->where(array('status'=>true, 'iffinish'=>false))->order('sort DESC,tryid DESC')->limit(10)->select();
        if($newList)
        {
            $tempNew = array();
            $num = 0;
            foreach($newList as $k => $v)
            {
                $tempNew[$num][] = $v;
                if(($k + 1) % 2 == 0)
                {
                    $num++;
                }
            }
            $newList = $tempNew;
        }
        $this->assign('newList', $newList);
        $this->assign('pageType', 'try');
        $this->display();
    }
    
    /**
     * 试用详情
     */
    public function detail()
    {
        $tryid = I('get.tryid');
        if(!$tryid)
        {
            header('Location:'.WEB_URL.U('Try/index'));
            exit;
        }
        $result=M('TryItems')->where(array('status'=>true,'tryid'=>$tryid))->find();
        $this->assign('info', $result);
        
        $count = 0;
        if($this->userid)
        {
            $count = M('TryApply')->where(array('userid'=>$this->userid, 'tryid'=>$result['tryid']))->count();
        }
        $this->assign('count', $count);
        
        $this->display();
    }
    
    /**
     * 提交申请
     */
    public function sendTry()
    {
        $this->isLogin(1);
        $tryid = I('get.tryid');
        if(!$tryid)
        {
            $this->error('参数错误');
        }
        $get['userid'] = $this->userid;
        $get['tryid'] = $tryid;
        $count = M('TryApply')->where(array('userid'=>$get['userid'], 'tryid'=>$get['tryid']))->count();
        if($count){
            $this->error('你已经申请该试用了,请等待审核');
        }
        $get['status']=false;
        $get['create_time']=time();
        $result=M('TryApply')->add($get);
        if($result){
            $data['requestnum'] = array('exp','requestnum+1');
            M('TryItems')->where(array('tryid'=>$get['tryid']))->save($data);
            $this->success('成功提交申请,请等待审核');
        }else{
            $this->error('申请出错,请稍候再试!');
        }        
    }

    /**
     * 报告列表
     */
    public function reportList()
    {
        $model = M('TryReport');
        $where['status'] = array('EQ', true);
        $count = $model->where($where)->count();
        $page = $this->Pages($count, 5);
        
        $list = $model
        ->where($where)
        ->field('*')
        ->order('id DESC')
        ->limit($page->firstRow . ',' . $page->listRows)
        ->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $where['infoid'] = $v['id'];
                $where['type'] = 3;
                $where['parent_id'] = 0;
                $list[$k]['msgnum'] = M('UserMessage')->where($where)->count();
                $list[$k]['url'] = U('Try/report?id='.$v['id']);
                $list[$k]['content'] = hy_substr($v['content'], 25);
                $list[$k]['username'] = hy_substr(M('User')->where(array('userid' => $v['userid']))->getField('nickname'), 8, true);
                $list[$k]['create_time'] = format_time($v['create_time'], 'Y-m-d');
            }
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign('list', $list);
        $this->display();
    }
    
    public function report()
    {
        $id = I('get.id');
        if(!intval($id))
        {
            header('Location:'.WEB_URL.U('Try/reportlist'));
            exit;
        }
        $model=New Model();
        $data=$model->table(array(
            C('DB_PREFIX').'try_report'=>'R',
            C('DB_PREFIX').'try_items'=>'I',
            C('DB_PREFIX').'user'=>'U'
        ))
        ->where('I.tryid=R.tryid and U.userid=R.userid and R.status=true and R.id='.$id)
        ->field('R.id,R.msgnum,I.title,I.price,I.buylink,U.openuid,U.uavatar,U.nickname,U.ifrz,R.create_time,R.content,R.image,R.otherpic')
        ->find();
        if(!$data)
        {
            header('Location:'.WEB_URL.U('Try/reportlist'));
            exit;
        }
        $data['create_time'] = format_time($data['create_time'], 'Y-m-d H:i');
        $data['image'] = $pic[] = WEB_URL.$data['image'];
        if($data['otherpic'] != '0')
        {
            $temp = explode('|', $data['otherpic']);
            foreach($temp as $k => $v)
            {
                $pic[] = WEB_URL.$v;
            }
        }
        $data['pic'] = $pic;
        $data['allpic'] = implode(',', $pic);
        $this->assign('info', $data);
        
        //评论
        $where['infoid']=$id;
        $where['type']=3;
        $where['parent_id'] = 0;
        $count = M('UserMessage')->where($where)->count();
        $this->assign('count', $count);
        // $limitRows = 5; // 设置每页记录数
        $limitRows = C('YF_PAGE');
        $page = $this->ajaxpage($count,$limitRows,'#msg','ajax_div','ajax_page_div');
        
        $msgModel=new Model();
        $message=$msgModel
        ->table(array(
            C('DB_PREFIX').'user_message'=>'M',
            C('DB_PREFIX').'user'=>'U',
        )
        )
        ->where('M.userid=U.userid and M.status=true and M.infoid='.$id.' and M.type=3 and M.parent_id=0')
        ->field('M.create_time,M.content,U.nickname,U.uavatar,U.openuid,U.uprovince,U.ucity,U.userid,M.id,M.touserid')
        ->order('M.create_time DESC')
        ->limit($page->firstRow . ',' . $page->listRows)
        ->select();
        
        //         foreach($message as $k=>$v){
        //             $message[$k]['touser']=M('User')->field('openuid,nickname')->where(array('userid'=>$v['touserid']))->find();
        //         }
        foreach($message as $k=>$v)
        {
            $child_temp = array();
            $child_temp = $msgModel->table(C('DB_PREFIX').'user_message')->field('*')->where(array('parent_id' => $v['id']))->order('create_time ASC')->select();
        
            $message[$k]['childlist'] = array();
            if($child_temp)
            {
                foreach($child_temp as $yk => $yv)
                {
                    if($yv['userid'] == 0)
                    {
        				$child_temp[$yk]['nickname'] = "烘焙圈";
        				$child_temp[$yk]['openuid'] = 0;
                    }
                    else
                    {
        				$yf_user = array();
        				$yf_user = M('User')->field('openuid, nickname, uprovince, ucity, uavatar, ifrz')->where(array('userid'=>$yv['userid']))->find();
        				$child_temp[$yk]['nickname'] = $yf_user['nickname'];
        				$child_temp[$yk]['openuid'] = $yf_user['openuid'];
        				$child_temp[$yk]['uprovince'] = $yf_user['uprovince'];
        				$child_temp[$yk]['ucity'] = $yf_user['ucity'];
        				$child_temp[$yk]['uavatar'] = $yf_user['uavatar'];
        				$child_temp[$yk]['ifrz'] = $yf_user['ifrz'];
                    }
                    if($yv['touserid'] != 0)
                    {
        				$child_temp[$yk]['touser'] = M('User')->field('openuid,nickname')->where(array('userid'=>$yv['touserid']))->find();
                    }
                    else
                    {
        				$child_temp[$yk]['touser']['nickname'] = "烘焙圈";
        				$child_temp[$yk]['touser']['openuid'] = 0;
                    }
                }
                $message[$k]['childlist'] = $child_temp;
            }
            $message[$k]['tempname'] = hy_substr($v['nickname'], 4, true);
            //$message[$k]['tempname'] = $v['nickname'];
            $message[$k]['touser'] = array();
            if(!empty($v['touserid']))
            {
                $message[$k]['touser']=M('User')->field('openuid,nickname')->where(array('userid'=>$v['touserid']))->find();
            }
        }
        $this->assign('msglist',$message);
        $this->assign('type', 3);
        $share['shareTitle'] = $data['title'];
        $share['shareDesc'] = hy_substr($data['content'], 30);
        $share['shareUrl'] = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_TIME'];
        $share['sharePic'] = $data['image'];
        $this->assign('share', $share);
        $this->getJsdk();
        $this->display();
    }
    
    public function addReport()
    {
        $tryid = I('get.id');
        if(!intval($tryid))
        {
            header('Location:'.WEB_URL.U('User/trylist'));
            exit;
        }
        $userid = $this->isLogin();
        $count = M('TryReport')->where(array('userid' => $userid, 'tryid' => $tryid))->count();
        if($count > 0)
        {
            header('Location:'.WEB_URL.U('User/trylist'));
            exit;
        }
        $title = M('TryItems')->where(array('tryid' => $tryid))->getField('title');
        
        $this->assign('title', $title);
        $this->assign('tryid', $tryid);
        $this->getJsdk();
        $this->display();
    }
    
    public function addInfo()
    {
        $this->isLogin(1);
        $post = I('post.');
        if(empty($post['content'])){
            $this->error('请填写试用报告简介');
        }
        if(count($post['all_pic']) > 0)
        {
            $arr = $this->getPic($_POST['all_pic']);
        }
        else
        {
            $this->error('请上传至少一张作品图');
        }
        $tempImg = explode('/', $arr['image']);
        $tempImg[count($tempImg) - 1] = str_replace('yf_', '', $tempImg[count($tempImg) - 1]);
        $post['image'] = implode('/', $tempImg);
        $post['otherpic'] = 0;
        $otheric = array();
        foreach($arr['thumb'] as $k => $v)
        {
            if($k > 0)
            {
                $temppic = explode('/', $v);
                $temppic[count($temppic) - 1] = str_replace('yf_', '', $temppic[count($temppic) - 1]);
                $otheric[] = implode('/', $temppic);
            }
        }
        if(count($otheric) > 0)
        {
            $post['otherpic'] = implode('|', $otheric);
        }
        unset($post['all_pic']);
        $post['cateid']=M('TryItems')->where(array('tryid'=>$post['tryid']))->getField('cateid');
        $post['create_time']=time();
        $post['userid']=$this->userid;
        $post['status']=true;
        $result=M('TryReport')->add($post);
        if($result){
            M('TryItems')->where(array('tryid'=>$post['tryid']))->setInc('iffinish',1);
            $this->success('试用报告发布成功',U('User/trylist'));
        }else{
            $this->error('试用报告发布失败,请稍候再试!');
        }
    }
    
    
}